package com.nku.mason.lucene.firstapp;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriter.MaxFieldLength;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import com.nku.mason.lucene.entity.Article;

public class LuceneTestFirst {
/**
 * 创建索引库的步骤
 * 	1. 创建Document对象
 *  2. 将实体类(Article)封装到Document对象中
 *  3. 创建IndexWriter对象,将Document对象写入索引库中
 *  	这里需要先使用Lucene中的工具类做一些初始化工作，比如确定索引库在文件系统中的位置(FSDirectory.open(new File(path)));
 *  	创建分词器，确定最大文本分析长度等。
 */
	public static void main(String[] args) {
		//createIndexDB();
		searchForKeyWord("南");
	}
	
	public static void createIndexDB(){
		
		Article article = new Article(1, "南开", "南开大学排名每况愈下");
		
		Document document = new Document();
		//参数一: document对象中封装的文本实体类的属性名，可以和实体类的字段名不一致，但为了之后的工具类方便通过反射实现，所以推荐命名一致
		//参数二: 封装在document对象中的实体类的字段值，注意document对象中封装的所有字段的类型都是String
		//参数三: 表示是否将该字段存于索引库中的原始记录表中，推荐初id以外的字段都保存
		//参数四: 表示是否对字段内容进行分词(存入词汇表中)，推荐除去id字段外都进行分词
		document.add(new Field("id", String.valueOf(article.getId()),Store.YES,Index.ANALYZED));
		document.add(new Field("title", article.getTitle(), Store.YES, Index.ANALYZED));
		document.add(new Field("content", article.getContent(), Store.YES, Index.ANALYZED));
		
		
		Directory directory;
		Version version = Version.LUCENE_30;
		Analyzer analyzer = new StandardAnalyzer(version);
		MaxFieldLength maxFieldLength = MaxFieldLength.LIMITED;
		IndexWriter indexWriter = null;
		try {
			directory = FSDirectory.open(new File("E:/TestDirectory/IndexDBa"));
			indexWriter = new IndexWriter(directory, analyzer, maxFieldLength);
			indexWriter.addDocument(document);
			System.out.println("Index Created...");
			System.out.println("----------------------------------------------");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				indexWriter.close();
			} catch (CorruptIndexException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
/**
 * 从Lucene索引库中搜索的步骤:
 * 1. 像创建索引库时一样，先做一些初始化工作，包括指定索引库在文件系统中的位置;
 * 2. 创建IndexSearcher对象，完成对关键字在索引库中的搜索
 * 		- 创建QueryParser对象，确定查询范围和使用的分词器，并将关键字包装起来供查询对象使用
 * 		- 创建Query对象，用IndexSearcher根据query来进行查询
 * 		- 处理返回的结果集 TopDocs 对象, 获取ScoreDoc数组，ScoreDoc对象的doc对应索引库中的原始记录表命中的标号
 * 		- 用IndexSearcher对象根据命中标号获取对应的Document对象
 */
	public static void searchForKeyWord(String keyword){
		
		List<Article> res = new ArrayList<>();
		
		Directory directory;
		Version version = Version.LUCENE_30;
		Analyzer analyzer = new StandardAnalyzer(version);
		IndexSearcher indexSearcher = null;
		int maxResultNum = 100;
		
		try {
			directory = FSDirectory.open(new File("E:/TestDirectory/IndexDBa"));
			indexSearcher = new IndexSearcher(directory);
			QueryParser queryParser = new QueryParser(version, "content", analyzer);
			Query query = queryParser.parse(keyword);
			TopDocs topDocs = indexSearcher.search(query, maxResultNum);
			ScoreDoc[] scoreDocs = topDocs.scoreDocs;
			for(ScoreDoc scoreDoc : scoreDocs){
				
				Document document = indexSearcher.doc(scoreDoc.doc);
				//System.out.println(document.get("id"));
				Article article = new Article(Integer.parseInt(document.get("id")), document.get("title"), document.get("content"));
				
				res.add(article);
			}
			
			for(Article a : res){
				System.out.println(a);
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				indexSearcher.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
